# ============================================================
# Appendix B — Tables & Conjoint Analyses
# Tablas usan ideología categórica (1–4 Left, 5–6 Center, 7–10 Right)
# Replication layout
# ============================================================

# ---- Paths ----
base_dir <- "~/Dropbox/Issue voting Chile"
data_dir <- file.path(base_dir, "09_replication/data")
fig_dir  <- file.path(base_dir, "09_replication/output")
dir.create(fig_dir, showWarnings = FALSE, recursive = TRUE)

# ---- Libraries ----
library(tidyverse)
library(haven)
library(janitor)
library(cregg)
library(ggplot2)
library(ggeasy)

# ---- Helpers ----
as_char <- function(x) as.character(as_factor(x))
save_fig <- function(filename, plot, width = 6, height = 5.4, dpi = 300) {
  ggsave(filename, plot = plot, width = width, height = height, dpi = dpi, bg = "white")
}

collapse_a6f <- function(x) {
  x_chr <- as_char(x)
  dplyr::case_when(
    x_chr %in% c("Muy de acuerdo", "De acuerdo") ~ "De/Muy de acuerdo",
    x_chr %in% c("Ni de acuerdo ni en desacuerdo", "En desacuerdo", "Muy en desacuerdo") ~
      "Neutro/Desacuerdo/Muy desacuerdo",
    TRUE ~ x_chr
  )
}


wave2_conjoint <- read_dta(file.path(data_dir, "wave2_conjoint.dta")) %>%
  mutate(weight = 1)

# ============================================================
# Tables
# ============================================================

# Ideology_cat (1–4 Left; 5–6 Center; 7–10 Right)
if ("A12" %in% names(wave2_conjoint)) {
  a12_chr <- as_char(wave2_conjoint$A12)
  a12_num <- suppressWarnings(as.numeric(a12_chr))
  a12_num[a12_chr == "Left"]  <- 1
  a12_num[a12_chr == "Right"] <- 10
  wave2_conjoint <- wave2_conjoint %>%
    mutate(
      ideology_num = a12_num,
      ideology_cat = cut(
        ideology_num,
        breaks = c(0, 4, 6, 10),
        labels = c("Left", "Center", "Right"),
        include.lowest = TRUE, right = TRUE
      )
    )
} else if (all(c("left","center","right") %in% names(wave2_conjoint))) {
  wave2_conjoint <- wave2_conjoint %>%
    mutate(
      ideology_cat = case_when(
        left   == 1 ~ "Left",
        center == 1 ~ "Center",
        right  == 1 ~ "Right",
        TRUE        ~ NA_character_
      ) |> factor(levels = c("Left","Center","Right"))
    )
} else if ("ideology" %in% names(wave2_conjoint)) {
  wave2_conjoint <- wave2_conjoint %>%
    mutate(ideology_cat = factor(as_char(ideology), levels = c("Left","Center","Right")))
} else {
  wave2_conjoint <- wave2_conjoint %>%
    mutate(ideology_cat = factor(NA_character_, levels = c("Left","Center","Right")))
}

# ---- a6f (colapsado) × ideology_cat (column %) ----
a6f_levels <- c("De/Muy de acuerdo", "Neutro/Desacuerdo/Muy desacuerdo")

tab_mano_by_ideol <- wave2_conjoint %>%
  mutate(
    a6f_collapsed = factor(collapse_a6f(a6f), levels = a6f_levels),
    ideology_cat  = factor(ideology_cat, levels = c("Left","Center","Right"))
  ) %>%
  filter(!is.na(a6f_collapsed), !is.na(ideology_cat)) %>%
  tabyl(a6f_collapsed, ideology_cat) %>%
  adorn_totals(c("row","col")) %>%   # Totales primero (mantiene numérico)
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1)

# Table  B1
tab_mano_by_ideol

# Distribución global de a6f (colapsado)
a6f_overall_pct <- prop.table(
  table(factor(collapse_a6f(wave2_conjoint$a6f), levels = a6f_levels), useNA = "no")
) * 100
a6f_overall_pct

# ---- feminist × ideology_cat (column %) ----
tab_fem_by_ideol <- wave2_conjoint %>%
  transmute(
    feminist = as_char(feminist),
    ideology_cat = factor(ideology_cat, levels = c("Left","Center","Right"))
  ) %>%
  filter(!is.na(feminist), !is.na(ideology_cat)) %>%
  tabyl(feminist, ideology_cat) %>%
  adorn_totals(c("row","col")) %>%   # Totales primero
  adorn_percentages("col") %>%
  adorn_pct_formatting(digits = 1)

# Table  B2
tab_fem_by_ideol

# ============================================================
# Conjoint setup — atributos & niveles
# ============================================================
atr <- c("a_1","a_2","a_3","a_4","a_5","a_6")
wave2_conjoint[, atr] <- lapply(wave2_conjoint[, atr], factor)

wave2_conjoint <- wave2_conjoint %>%
  mutate(
    Ideology    = a_1,
    Gender      = a_2,
    Age         = a_3,
    Feminism    = a_4,
    Immigration = a_5,
    Crime       = a_6
  )

wave2_conjoint$Ideology    <- factor(wave2_conjoint$Ideology,    levels = c("Right","Left"))
wave2_conjoint$Feminism    <- factor(wave2_conjoint$Feminism,    levels = c("Non-Feminist","Feminist"))
wave2_conjoint$Crime       <- factor(wave2_conjoint$Crime,       levels = c("No Harsher Punishment","Harsher Punishment"))
wave2_conjoint$Immigration <- factor(wave2_conjoint$Immigration, levels = c("No Restrictions","New Immigration Restrictions"))

# ============================================================
# Figure B2. Conjoint — Left & Feminism subset (left_feminist == 1)
# ============================================================
left_fem_sub <- subset(wave2_conjoint, left_feminist == 1)
left_fem_sub$profile1 <- interaction(left_fem_sub$Ideology, left_fem_sub$Feminism, sep = "_")

mm_left_fem <- mm(
  left_fem_sub,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid
)
mm_left_fem$feature <- ifelse(mm_left_fem$feature == "profile1", "Ideology*Feminism", mm_left_fem$feature)

plt_left_fem <- plot(mm_left_fem[c(2,4,1,3), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_Feminist"       = "Left and Feminist",
    "Left_Non-Feminist"   = "Left and Non-Feminist",
    "Right_Feminist"      = "Right and Feminist",
    "Right_Non-Feminist"  = "Right and Non-Feminist"
  )) +
  theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = "none") +
  scale_x_continuous(limits = c(0,1), breaks = seq(0,1,0.2)) +
  labs(title = "Left Feminist") +
  easy_center_title() +
  theme(
    plot.title  = element_text(size = 16, color = "black"),
    axis.text.x = element_text(size = 14, color = "black"),
    axis.text.y = element_text(size = 14, color = "black"),
    axis.title.x = element_blank()
  ) +
  geom_point(size = 2)

save_fig(file.path(fig_dir, "mm_left_fem2.png"), plt_left_fem, width = 5, height = 5.4)

# ============================================================
# Figure B2. Conjoint — Right & Non-Feminist subset (right==1 & feminist==0)
# ============================================================
right_non_fem_sub <- subset(wave2_conjoint, right == 1 & feminist == 0)
right_non_fem_sub$profile1 <- interaction(right_non_fem_sub$Ideology, right_non_fem_sub$Feminism, sep = "_")

mm_right_non_fem <- mm(
  right_non_fem_sub,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid
)
mm_right_non_fem$feature <- ifelse(mm_right_non_fem$feature == "profile1", "Ideology*Feminism", mm_right_non_fem$feature)

plt_right_non_fem <- plot(mm_right_non_fem[c(3,1,4,2), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_Feminist"       = "Left and Feminist",
    "Left_Non-Feminist"   = "Left and Non-Feminist",
    "Right_Feminist"      = "Right and Feminist",
    "Right_Non-Feminist"  = "Right and Non-Feminist"
  )) +
  theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = "none") +
  scale_x_continuous(limits = c(0,1), breaks = seq(0,1,0.2)) +
  labs(title = "Right Non-Feminist") +
  easy_center_title() +
  theme(
    plot.title  = element_text(size = 16, color = "black"),
    axis.text.x = element_text(size = 14, color = "black"),
    axis.text.y = element_text(size = 14, color = "black"),
    axis.title.x = element_blank()
  ) +
  geom_point(size = 2)

save_fig(file.path(fig_dir, "mm_right_non_fem2.png"), plt_right_non_fem, width = 5, height = 5.4)

# ============================================================
# Figure B1. Conjoint — Crime × Ideology (Left subset que acuerda con mano dura)
# ============================================================
left_crime <- subset(wave2_conjoint, left == 1 & (as_char(a6f) %in% c("Muy de acuerdo","De acuerdo")))
left_crime$profile1 <- interaction(left_crime$Ideology, left_crime$Crime, sep = "_")

mm_left_crime <- mm(
  left_crime,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid
)
mm_left_crime$feature <- ifelse(mm_left_crime$feature == "profile1", "Ideology*Crime", mm_left_crime$feature)

plt_left_crime <- plot(mm_left_crime[c(2,4,1,3), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_More Punitive"  = "Left and More Punitive",
    "Left_Less Punitive"  = "Left and Less Punitive",
    "Right_More Punitive" = "Right and More Punitive",
    "Right_Less Punitive" = "Right and Less Punitive"
  )) +
  theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = "none") +
  scale_x_continuous(limits = c(0,1), breaks = seq(0,1,0.2)) +
  labs(title = "Left and More Punitive") +
  easy_center_title() +
  theme(
    plot.title  = element_text(size = 12),
    axis.text.x = element_text(size = 10, color = "black"),
    axis.text.y = element_text(size = 10,  color = "black"),
    axis.title.x = element_blank()
  )

save_fig(file.path(fig_dir, "mm_left_crime.png"), plt_left_crime, width = 5, height = 5.4)

# ============================================================
# Figure B1. Conjoint — Crime × Ideology (Right subset que acuerda con mano dura)
# ============================================================
right_crime <- subset(wave2_conjoint, right == 1 & (as_char(a6f) %in% c("Muy de acuerdo","De acuerdo")))
right_crime$profile1 <- interaction(right_crime$Ideology, right_crime$Crime, sep = "_")

mm_right_crime <- mm(
  right_crime,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid
)
mm_right_crime$feature <- ifelse(mm_right_crime$feature == "profile1", "Ideology*Crime", mm_right_crime$feature)

plt_right_crime <- plot(mm_right_crime[c(1,3,2,4), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Right_More Punitive" = "Right and More Punitive",
    "Right_Less Punitive" = "Right and Less Punitive",
    "Left_More Punitive"  = "Left and More Punitive",
    "Left_Less Punitive"  = "Left and Less Punitive"
  )) +
  theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = "none") +
  scale_x_continuous(limits = c(0,1), breaks = seq(0,1,0.2)) +
  labs(title = "Right and More Punitive") +
  easy_center_title() +
  theme(
    plot.title  = element_text(size = 12),
    axis.text.x = element_text(size = 10, color = "black"),
    axis.text.y = element_text(size = 10, color = "black"),
    axis.title.x = element_blank()
  )

save_fig(file.path(fig_dir, "mm_right_crime.png"), plt_right_crime, width = 5, height = 5.4)

# ============================================================
# Figure B3. Conjoint — Triple (Ideology × Immigration × Crime) — Left
# ============================================================
left_fem_mig <- subset(wave2_conjoint, left_crime_mig == 1)
left_fem_mig$profile2 <- interaction(left_fem_mig$Ideology, left_fem_mig$Immigration, left_fem_mig$Crime, sep = "_")

mm_left_fem_mig <- mm(
  left_fem_mig,
  choice_clean2 ~ profile2 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid
)
mm_left_fem_mig$feature <- ifelse(mm_left_fem_mig$feature == "profile2", "Ideology*Immigration*Crime", mm_left_fem_mig$feature)

plt_left_fem_mig <- plot(mm_left_fem_mig[c(1,3,5,7,4,2,6,8), ], vline = 0.5) +
  theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = "none") +
  scale_x_continuous(limits = c(0,1), breaks = seq(0,1,0.2)) +
  labs(title = "Left, Crime, Pro Immigration") +
  easy_center_title() +
  theme(
    plot.title  = element_text(size = 12),
    axis.text.x = element_text(size = 10, color = "black"),
    axis.text.y = element_text(size = 10, color = "black"),
    axis.title.x = element_blank()
  )

save_fig(file.path(fig_dir, "mm_left_fem_mig.png"), plt_left_fem_mig, width = 6, height = 5.4)

# ============================================================
# Figure B3. Conjoint — Triple (Ideology × Immigration × Crime) — Right
# ============================================================
right_non_fem_mig <- subset(wave2_conjoint, right_crime_mig == 1)
right_non_fem_mig$profile2 <- interaction(right_non_fem_mig$Ideology, right_non_fem_mig$Immigration, right_non_fem_mig$Crime, sep = "_")

mm_right_fem_mig <- mm(
  right_non_fem_mig,
  choice_clean2 ~ profile2 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid
)
mm_right_fem_mig$feature <- ifelse(mm_right_fem_mig$feature == "profile2", "Ideology*Immigration*Crime", mm_right_fem_mig$feature)

plt_right_fem_mig <- plot(mm_right_fem_mig[c(2,4,6,8,1,3,5,7), ], vline = 0.5) +
  theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = "none") +
  scale_x_continuous(limits = c(0,1), breaks = seq(0,1,0.2)) +
  labs(title = "Right, Crime, Anti-Immigration") +
  easy_center_title() +
  theme(
    plot.title  = element_text(size = 12),
    axis.text.x = element_text(size = 10, color = "black"),
    axis.text.y = element_text(size = 10, color = "black"),
    axis.title.x = element_blank()
  )

save_fig(file.path(fig_dir, "mm_right_fem_mig.png"), plt_right_fem_mig, width = 6, height = 5.4)

